<!--
 * @Author: levi7754 levi7754@163.com
 * @Date: 2025-10-11 18:00:27
 * @LastEditors: levi7754 levi7754@163.com
 * @LastEditTime: 2025-10-13 14:08:07
 * @FilePath: \udp-nature-mall\components\s-goods-card\s-goods-card.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 商品卡片 -->
  <view>
    <!-- 1 100%宽卡片列表-->
    <view v-if="mode === 1 && state.goodsList.length" class="goods-sl-box">
      <view
          class="goods-box"
          v-for="item in state.goodsList"
          :key="item.id"
          :style="[{ marginBottom: data.space * 2 + 'rpx' }]"
      >
        <s-goods-column
            class=""
            size="sl"
            :goodsFields="goodsFields"
            :tagStyle="tagStyle"
            :data="item"
            :titleColor="goodsFields.title?.color"
            :subTitleColor="goodsFields.subtitle.color"
            :topRadius="data.borderRadiusTop"
            :bottomRadius="data.borderRadiusBottom"
            @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
        >
          <template #cart>
            <view class="ut-cart-slot">
              <button class="ss-reset-button cart-btn" :style="[buyStyle]">
                {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
              </button>
            </view>
          </template>
        </s-goods-column>
      </view>
    </view>

    <!-- 2   双列瀑布流列表-->
    <view
        v-if="mode === 2 && state.goodsList.length"
        class="goods-md-wrap ss-flex ss-flex-wrap ss-col-top"
    >
      <view class="goods-list-box">
        <view
            class="left-list"
            :style="[{ paddingRight: data.space + 'rpx', marginBottom: data.space + 'px' }]"
            v-for="item in state.leftGoodsList"
            :key="item.id"
        >
          <s-goods-column
              class="goods-md-box"
              size="md"
              :goodsFields="goodsFields"
              :tagStyle="tagStyle"
              :data="item"
              :titleColor="goodsFields.title?.color"
              :subTitleColor="goodsFields.subtitle.color"
              :topRadius="data.borderRadiusTop"
              :bottomRadius="data.borderRadiusBottom"
              :titleWidth="330 - marginLeft - marginRight"
              @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
              @getHeight="mountMasonry($event, 'left')"
          >
            <template v-slot:cart>
              <button class="ss-reset-button cart-btn" :style="[buyStyle]">
                {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
              </button>
            </template>
          </s-goods-column>
        </view>
      </view>
      <view class="goods-list-box">
        <view
            class="right-list"
            :style="[{ paddingLeft: data.space + 'rpx', marginBottom: data.space + 'px' }]"
            v-for="item in state.rightGoodsList"
            :key="item.id"
        >
          <s-goods-column
              class="goods-md-box"
              size="md"
              :goodsFields="goodsFields"
              :tagStyle="tagStyle"
              :data="item"
              :titleColor="goodsFields.title?.color"
              :subTitleColor="goodsFields.subtitle.color"
              :topRadius="data.borderRadiusTop"
              :bottomRadius="data.borderRadiusBottom"
              :titleWidth="330 - marginLeft - marginRight"
              @click="sheep.$router.go('/pages/goods/index', { id: item.id })"
              @getHeight="mountMasonry($event, 'right')"
          >
            <template v-slot:cart>
              <button class="ss-reset-button cart-btn" :style="[buyStyle]">
                {{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
              </button>
            </template>
          </s-goods-column>
        </view>
      </view>
    </view>

    <!-- 3  30%卡片列表-->
    <view v-if="mode === 3 && state.goodsList.length" class="goods-lg-box">
      <view
          class="goods-box"
          :style="[{ marginBottom: data.space + 'px' }]"
          v-for="item in state.goodsList"
          :key="item.id"
      >
        <s-goods-column
            class="goods-card"
            size="lg"
            :goodsFields="goodsFields"
            :data="item"
            :tagStyle="tagStyle"
            :category="params.category"
            :titleColor="goodsFields.title?.color"
            :subTitleColor="goodsFields.subtitle.color"
            :topRadius="data.borderRadiusTop"
            :bottomRadius="data.borderRadiusBottom"
            @tap="sheep.$router.go('/pages/goods/index', { id: item.id, from })"
        >
          <template v-slot:cart>
            <view v-if="customer.customer_name">
              <!-- <view v-if="params.category === 'sample'" class="cart-btn ut-smaple-tag">
                <uni-tag :text="$t('mall.sample_submitted')" style="background-color: #EA0D2C; border-color: #EA0D2C;" />
              </view> -->
              <button class="ss-reset-button cart-btn" :style="[buyStyle]" @click.stop="onTap(item, 'isSample')">
                <view style="display: flex; align-items: center; justify-content: center;">
                  <uni-icons custom-prefix="ucon" type="ucon-cart" size="24" color="#EA0D2C"></uni-icons>
                  {{ buyNowStyle.mode === 1 ? "sample" : '' }}
                </view>
              </button>
              <button class="ss-reset-button cart-btn cart-btn-right" :style="[buyStyle]" @click.stop="onTap(item)">
                <view style="display: flex; align-items: center; justify-content: center;">
                  <uni-icons custom-prefix="ucon" type="ucon-cart" size="24" color="#EA0D2C"></uni-icons>
                  {{ buyNowStyle.mode === 1 ? "cart" : '' }}
                </view>
              </button>
            </view>
            <view v-else/>
          </template>
        </s-goods-column>
      </view>
    </view>
    <uni-load-more
        v-if="state.pagination.total > 0"
        :status="state.loadStatus"
        :content-text="{
       contentdown: '上拉加载更多',
     }"
        @tap="loadmore"
    />
    <s-empty v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" :text="$t('app.empty')" />
    <!-- 规格与数量弹框 -->
    <s-select-sku
      v-if="state.showSelectSku"
      :goodsInfo="state.goodsInfo"
      :show="state.showSelectSku"
      @addCart="onAddCart"
      @buy="onBuy"
      @change="onSkuChange"
      @close="state.showSelectSku = false"
    />
  </view>
</template>

<script setup>
/**
 * 商品模板，装修商品卡片
 * @description style 1:带tab 2：瀑布流，横向两个，上图下内容 3：大图，横向一个
 */
import { computed, reactive, onMounted, watch } from 'vue';
import { onReachBottom } from '@dcloudio/uni-app';
import { useI18n } from "vue-i18n"
import { useStore } from "vuex"
import { udp, fileUrl } from "@/utils"
import { ajax } from "@/http"

const pagination = {
  data: [],
  page: 1,
  total: 0,
  size: 10
};

const store = useStore()
const customer = computed(() => store.state.customer.current); 

const { t } = useI18n()

watch(() => customer.value,
	(nv, ov) => {
		nv.id !== ov?.id && getList()
	})

const state = reactive({
  pagination: {
    page: 1,
    total: 0,
    size: 6
  },
  loadStatus: "",
  goodsList: [],
  leftGoodsList: [],
  rightGoodsList: [],
  showSelectSku: false,
  goodsInfo: {}
});
const props = defineProps({
  data: {
    type: Object,
    default() {},
  },
  styles: {
    type: Object,
    default() {},
  },
  params: {
    type: Object,
    default() {},
  },
  from: {
    type: String,
    default: ""
  }
});
async function loadmore() {
  if (state.loadStatus !== "noMore") {
    state.pagination.page++;
    await getList();
  }
}
const { mode, tagStyle, buyNowStyle, goodsFields, goodsIds } = props.data ?? {};
const { marginLeft, marginRight } = props.styles ?? {};

async function getGoodsListByIds(ids) {
  let { data } = await sheep.$api.goods.ids({ ids });
  return data;
}

async function getList() {
  state.loadStatus = 'loading'
  
  const user = uni.getStorageSync("kUserInfo")
  const sale_department_id = user?.saleDepartmentVOList[0]?.id
  const page = state.category_id === props.params.category_id ? state.pagination.page : 1
  const params = {
    enabled: '1',
    sale_department_id,
    currPage: page,
    pageSize: state.pagination.size,
    ...props.params
  }
  // 客户信息
  customer && Object.assign(params, { customerName: customer.name })
  state.category_id = props.params.category_id
  const res = await ajax.get("/nature-business/api/spu", params)
  // const res = await sheep.$api.goods.list(params);
  uni.hideLoading();
  // const res = testList()
  console.log({res})
  if (res.code === "500") {
    state.pagination.data = [];
    state.pagination.total = 0;
    state.goodsList = [];
    state.loadStatus = 'noMore'
    return
  }
  const {list,totalCount, totalPage } = res;
  list?.forEach(f => {
    f.primaryPictureUrl = f.primary_picture_url ?  fileUrl + JSON.parse(f.primary_picture_url).url : ""
  })
  console.log("page", page)
  let goodsList = page !== 1 ? state.goodsList.concat(list) : list;
  if (page === 1) {
    count = 0
    state.leftGoodsList = []
    state.rightGoodsList = []
  }
  state.pagination.data = goodsList;
  state.pagination.total = totalCount;
  state.goodsList = goodsList;
  console.log("goodsList", goodsList, page)
  mountMasonry();
  if (page < totalPage){
    state.loadStatus = 'more'
  }else {
    state.loadStatus = 'noMore'
  }
  console.log('res', res)
}

let isSample = false
const onTap = (item, sampleFlag) => {
  isSample = sampleFlag
  // getProductInfo(item)
}

// 规格变更
  function onSkuChange(e) {
    console.log('e',e)
    state.selectedSkuPrice = e;
  }

  // 添加购物车
  function onAddCart(e) {
    e.isSample = isSample
    console.log('onAddCart', e)
    sheep.$store('cart').add(e).then(res => {
      state.showSelectSku = false
      sheep.$helper.toast(t("tip.addSuccess"))
    });
  }

  function onBuy(e) {
    console.log('下单物品：',e)
    e.quantity = e.buyNum
    let str = "";
    const obj = JSON.parse(e.sku_specs);
    Object.keys(obj).forEach(key => {
      str += key + "：" + obj[key] + " ";
    });
    e.spDataValue = str;
    e.productName = e.name
    sheep.$router.go('/pages/order/confirm', {
      data: JSON.stringify({
        order_type: 'goods',
        goods_list: [
          {
            goods_id: e.productId,
            goods_num: e.buyNum,
            skuId: e.id,
            ...e
          },
        ],
      }),
    });
    state.showSelectSku = false
  }

const getProductInfo = (item) => {
  uni.showLoading()
  setTimeout(() => {
    uni.hideLoading()
    state.goodsInfo = {
      product: {
        albumPics: "https://img.alicdn.com/imgextra/i2/2206384590783/O1CN01g54m3P1HeeoltaDG1_!!2206384590783.jpg_.webp,https://img.alicdn.com/imgextra/i3/2206384590783/O1CN01p43wBP1HeeopYdMkB_!!0-item_pic.jpg_.webp",
        brandName: "大自然家居",
        detailMobileHtml: "<img src='https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif'/><img src='https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif' /><img src='https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif' />",
        name: item.name,
        price: item.price,
        productAttr: "[{\"name\":\"item_name\",\"options\":[\"DTS-02 8mm w pad\",\"DTS-03 8mm w pad\",\"DTS-05 8mm w pad\"]},{\"name\":\"wood_species\",\"options\":[9999]},{\"name\":\"structure\",\"options\":[\"ssss\",\"aaaaa\"]},{\"name\":\"colour\",\"options\":[\"yello\",\"red\",\"skyblue\"]}]",
        productCategoryName: "地板",
        pic: "https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif",
      },
      skus: [
        {
          id: item.id + 100,
          createBy: 1,
          createTime: "2025-05-07 15:03:20",
          outSkuId: null,
          name: item.name,
          uid: item.uid,
          pic: "https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif",
          price: item.price,
          productId: item.id,
          sku_specs: "{\"item_name\":\"DTS-02 8mm w pad\",\"wood_species\":9999,\"structure\":\"ssss\",\"colour\":\"yello\"}",
          stock: 1000,
          updateBy: 1,
          updateTime: "2025-05-07 15:04:32"
        },
      ]
    };
    state.showSelectSku = true
  }, 1000);
}

function testList() {
  const content = [
    {
      id: 1,
      uid: sheep.$helper.guid(),
      isSapmled: 1,
      name: "SPC-DTS-01",
      pic: 'https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif',
      price: Math.floor(Math.random() * 1000),
      original_price: Math.floor(Math.random() * 5000),
      stock: Math.floor(Math.random() * 1000),
    },
    {
      id: 2,
      uid: sheep.$helper.guid(),
      name: "SPC-DTS-02",
      isSapmled: 1,
      pic: 'https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif',
      price: Math.floor(Math.random() * 1000),
      original_price: Math.floor(Math.random() * 5000),
      stock: Math.floor(Math.random() * 1000),
    },
    {
      id: 3,
      uid: sheep.$helper.guid(),
      name: "SPC-DTS-03",
      isSapmled: 1,
      pic: 'https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif',
      price: Math.floor(Math.random() * 1000),
      original_price: Math.floor(Math.random() * 5000),
      stock: Math.floor(Math.random() * 1000),
    },
    {
      id: 4,
      uid: sheep.$helper.guid(),
      name: "SPC-DTS-04",
      isSapmled: 1,
      pic: 'https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif',
      price: Math.floor(Math.random() * 1000),
      original_price: Math.floor(Math.random() * 5000),
      stock: Math.floor(Math.random() * 1000),
    },
    {
      id: 5,
      uid: sheep.$helper.guid(),
      name: "SPC-DTS-05",
      isSapmled: 1,
      pic: 'https://img30.360buyimg.com/sku/jfs/t1/240188/9/14657/75818/66dfea07F35596e2c/9d43b50c3aaa8137.jpg.avif',
      price: Math.floor(Math.random() * 1000),
      original_price: Math.floor(Math.random() * 5000),
      stock: Math.floor(Math.random() * 1000),
    }
  ]
  return { content, totalElements: 6, totalPages: 1 }
}

// 上拉加载更多
onReachBottom(() => {
  loadmore();
});
onMounted(async () => {
  await getList()
  if (mode === 2) {
    mountMasonry();
  }
});

// 加载瀑布流
let count = 0;
let leftHeight = 0;
let rightHeight = 0;

function mountMasonry(height = 0, where = 'left') {
  if (!state.goodsList[count]) return;
  if (count %2 === 0) {
    state.leftGoodsList.push(state.goodsList[count]);
  } else {
    state.rightGoodsList.push(state.goodsList[count]);
  }
  console.log(state.leftGoodsList)
  // if (!state.goodsList[count]) return;
  // if (where === 'left') leftHeight += height;
  // if (where === 'right') rightHeight += height;
  // if (leftHeight <= rightHeight) {
  //   state.leftGoodsList.push(state.goodsList[count]);
  // } else {
  //   state.rightGoodsList.push(state.goodsList[count]);
  // }
  count++;
}

// 购买按钮样式
const buyStyle = computed(() => {
  if (buyNowStyle.mode == 1) {
    // button
    return {
      background: `linear-gradient(to right, ${buyNowStyle.color1}, ${buyNowStyle.color2})`,
    };
  }

  if (buyNowStyle.mode == 2) {
    // image
    return {
      width: '54rpx',
      height: '54rpx',
      background: `url(${sheep.$url.cdn(buyNowStyle.src)}) no-repeat`,
      backgroundSize: '100% 100%',
    };
  }
});
defineExpose({ getList })
</script>

<style lang="scss" scoped>
.goods-md-wrap {
  width: 100%;
}

.goods-list-box {
  width: 50%;
  box-sizing: border-box;
  .left-list {
    &:nth-last-child(1) {
      margin-bottom: 0 !important;
    }
  }
  .right-list {
    &:nth-last-child(1) {
      margin-bottom: 0 !important;
    }
  }
}

.goods-box {
  &:nth-last-of-type(1) {
    margin-bottom: 0 !important;
  }
}

.goods-md-box,
.goods-sl-box,
.goods-lg-box {
  position: relative;

  .cart-btn {
    position: absolute;
    bottom: 18rpx;
    // right: 20rpx;
    right: 6rpx;
    z-index: 11;
    // height: 60rpx;
    line-height: 50rpx;
    padding: 0 10rpx;
    // padding: 0 20rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    color: #fff;

    width: 100rpx;
  }
  .cart-btn-right {
    bottom: 90rpx;
    // right: 80rpx;
  }
  .ut-smaple-tag {
    right: 160rpx;
    bottom: 60rpx;
    border-radius: 16rpx;
    width: 240rpx;
  }
}

.circular {
	width: 300px;
	height: 300px;
  position:absolute;
}
.circular path {
  fill: none;
}
.circular svg {
  display: block;
  overflow: visible;
  transform: rotate(-55deg);
}
.circular svg text {
  letter-spacing: 2px;
  fill:black;
  font-size: 12px;
}
</style>
